package com.dcits.idea.processor;

import com.intellij.ide.fileTemplates.impl.UrlUtil;
import com.intellij.util.io.URLUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;

/**
 * @Author tangmqb DCITS
 * @DATE 2021/11/4 14:57
 * @Version 1.0.0
 */
public class MDFreeMarkerProcess extends FreemarkerProcessor {
    @Override
    protected Object getModel(SourceDataNode sourceDataNode) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("topic", sourceDataNode.getTopic());
        map.put("dataList", sourceDataNode.getNodeDataList());
        return map;
    }

    @Override
    protected Template getTemplate() throws IOException {
        Configuration config = new Configuration(Configuration.VERSION_2_3_30);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        String templateContent = UrlUtil.loadText(MDFreeMarkerProcess.class.getResource("/template/note.ftl"));
        stringTemplateLoader.putTemplate("MDTemplate",templateContent);
        config.setTemplateLoader(stringTemplateLoader);
        return config.getTemplate("MDTemplate");
    }

    @Override
    protected Writer getWriter(SourceDataNode sourceDataNode) throws Exception {
        String filePath = sourceDataNode.getFilePath();
        File file = new File(filePath);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));

        return bufferedWriter;
    }
}
